from datetime import datetime, timedelta
from typing import Annotated, Optional

from fastapi import APIRouter, Depends, BackgroundTasks, Request, Body

from sanren.utils import get_current_active_user, Helper
from application.http import models
from application.http.models import OemModel, CodeModel
from application.http.schemas import ApiSchemas
from application.http import schemas
from application.config import appSettings
from application.tasks import abolish_task


router = APIRouter(prefix='/code', tags=['Code'])
module_name = '码管理模块 - 作废单'


def func(*args, **kwargs):
    # 作废码
    print('===================作废码', args, kwargs)


@router.post('/abolishs/restore-batch', response_model=schemas.BaseApiOut)
def abolish_restore_batch(
    current_user: Annotated[object, Depends(get_current_active_user)],
    background_tasks: BackgroundTasks,
    request: Request,
    post: object = Body(...),
):
    """
        作废码单 批量还原
    """

    restore_list = []
    for id in post.ids:
        obj = CodeModel.Abolish.where('id', id).first()
        if obj is None:
            return schemas.BaseApiOut(code=1, message='作废码单不存在')
        if obj.status != 2:
            return schemas.BaseApiOut(code=1, message='只有完成的作废单才能进行还原操作')

        restore_list.append(obj)

    try:
        # 批量还原
        for abolish in restore_list:
            job_args = [abolish.id]
            background_tasks.add_task(abolish_task.abolish_restore_job, *job_args)
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.post('/abolishs/generation/{id}', response_model=schemas.BaseApiOut)
def generation_abolish(
    current_user: Annotated[object, Depends(get_current_active_user)],
    background_tasks: BackgroundTasks,
    request: Request,
    id: int,
):
    """
        作废码单生成
    """
    obj = CodeModel.Abolish.where('id', id).first()
    if obj is None:
        return schemas.BaseApiOut(code=1, message='作废码单不存在')
    if obj.status != 0 and obj.status != 4:
        return schemas.BaseApiOut(code=1, message='作废单只有末开始和错误单能进行作废操作')

    try:
        # 作废码
        job_args = [obj.id]
        background_tasks.add_task(abolish_task.abolish_job, *job_args)

        # 更新生码状态 为 1 开始作废
        obj.status = 1
        obj.save()
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.post('/abolishs/restore/{id}', response_model=schemas.BaseApiOut)
def abolish_restore(
    current_user: Annotated[object, Depends(get_current_active_user)],
    background_tasks: BackgroundTasks,
    request: Request,
    id: int,
):
    """
        作废码单生成
    """
    obj = CodeModel.Abolish.where('id', id).first()
    if obj is None:
        return schemas.BaseApiOut(code=1, message='作废码单不存在')
    if obj.status != 2:
        return schemas.BaseApiOut(code=1, message='只有完成的作废单才能进行还原操作')

    try:
        # 作废码
        job_args = [obj.id]
        background_tasks.add_task(abolish_task.abolish_restore_job, *job_args)
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.get('/abolishs', response_model=schemas.BaseApiListOut)
async def get_orders(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    status: Optional[str | int] = None,
    code: Optional[str] = None,
    keyword: Optional[str] = None,
):
    """
        码管理 作废码单列表
    """

    objs = CodeModel.Abolish.with_('brand')

    if code:
        objs = objs.where('company_code', code)

    if status:
        objs = objs.where('status', status)

    if keyword:
        objs = objs.where(
            lambda query: query.where(
                'batch_sn', 'like', f'%{keyword}%'
            ).or_where(
                'company_name', 'like', f'%{keyword}%'
            ).or_where(
                'order_sn', 'like', f'%{keyword}%'
            )
        )

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    return objs.serialize()


@router.post('/abolishs', response_model=schemas.BaseApiOut)
async def add_abolish(
    current_user: Annotated[object, Depends(get_current_active_user)],
    background_tasks: BackgroundTasks,
    request: Request,
    post: ApiSchemas.code.AbolishCreate,
):
    """
        添加作废单
    """

    company = OemModel.Company.where('code', post.company_code).first()
    if company is None:
        return schemas.BaseApiOut(code=1, message='企业不存在')
    if post.batch_sn is None or post.batch_sn == '':
        return schemas.BaseApiOut(code=1, message='批次号不能为空')
    obj_order = CodeModel.Order.where('batch_sn', post.batch_sn).first()
    if obj_order is None:
        return schemas.BaseApiOut(code=1, message='批次号对应生码单不存在')
    if post.scope_status == 2 and (post.scope_file is None or post.scope_file == ''):
        return schemas.BaseApiOut(code=1, message='部分作废时，作废文件为必要参数')
    if post.scope_status == 1:
        post.scope_file = None
        scope_type = None
    else:
        scope_type = post.scope_type

    batch_num = Helper.batch_sn_decode(post.batch_sn)

    try:
        obj = CodeModel.Abolish.create(
            company_code=post.company_code.lower(),
            company_name=company.name,
            batch_sn=post.batch_sn,
            batch_num=batch_num,
            scope_status=post.scope_status,
            scope_type=scope_type,
            scope_file=post.scope_file,
            counts=0,
            remarks=post.remarks,
            status=0,
        )

        print('操作成功:', obj.fresh().id)
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.get('/abolishs/{id}', response_model=schemas.BaseApiOut)
async def get_abolish(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
):
    """
        生码单详情
    """

    obj = CodeModel.Order.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此生码单不存在')

    return {'data': obj.serialize()}


@router.put('/abolishs/{id}', response_model=schemas.BaseApiOut)
async def edit_abolish(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: ApiSchemas.code.AbolishCreate,
    id: int,
):
    """
        编辑作废单
    """

    obj = CodeModel.Abolish.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此信息不存在')

    try:
        # 更新备注
        obj.remarks = post.remarks
        obj.save()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.delete('/abolishs/{id}', response_model=schemas.BaseApiOut)
async def delete_abolish(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
):
    """
        取消作废单
    """

    obj = CodeModel.Abolish.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此信息不存在')

    try:
        # 取消
        obj.status = 3
        obj.save()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}
